package com.coder520.mamabike.b.manager;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.Preference;
import android.text.TextUtils;

import com.coder520.mamabike.b.MyApplication;
import com.coder520.mamabike.b.entity.BikeLockTo;
import com.coder520.mamabike.b.internet.DataListener;
import com.coder520.mamabike.b.internet.DefaultResponseDispatcher;
import com.coder520.mamabike.b.internet.InternetRequestWorker;
import com.coder520.mamabike.b.internet.net.BikeInterface;

/**
 * Created by zhongyanli on 2017/10/13.
 */

public class BikeManager {
    private static final String TAG = BikeManager.class.getSimpleName();
    private static final String PREFERENCE_KEY_BIKE_NUMBER = "preference_key_bike";
    private BikeInterface mBikeInterface;
    private static BikeManager sInstance;
    private BikeManager() {
        mBikeInterface = InternetRequestWorker.getInstance().create(BikeInterface.class);
    }
    public static BikeManager getInstance() {
        if (sInstance == null) {
            sInstance = new BikeManager();
        }
        return sInstance;
    }
    private Long mCurrentBikeNumber;
    public void setCurrentBikeNumber(String bikeNumber) {
        if (TextUtils.isEmpty(bikeNumber)) {
            return;
        }
        this.mCurrentBikeNumber = Long.valueOf(bikeNumber);
        SharedPreferences preference = MyApplication.getApplication().getSharedPreferences(
                TAG, Context.MODE_PRIVATE);
        preference.edit().putLong(PREFERENCE_KEY_BIKE_NUMBER, mCurrentBikeNumber).apply();
    }
    public static boolean isRightBikeNumber(Long bikeNumber) {
        return bikeNumber != null && bikeNumber > 0;
    }
    public Long getCurrentBikeNumber() {
        if (!isRightBikeNumber(mCurrentBikeNumber)) {
            SharedPreferences preference = MyApplication.getApplication().getSharedPreferences(
                    TAG, Context.MODE_PRIVATE);
            mCurrentBikeNumber = preference.getLong(PREFERENCE_KEY_BIKE_NUMBER, -1L);
        }
        return mCurrentBikeNumber;
    }

    public void lockBike(BikeLockTo bikeLockTo, DataListener dataListener) {
        InternetRequestWorker.getInstance().asyncNetwork(mBikeInterface.lockBike(bikeLockTo),
                new DefaultResponseDispatcher(dataListener));
    }
    public void queryBikeState(Long bikeNumber, DataListener<Integer> dataListener) {
        InternetRequestWorker.getInstance().asyncNetwork(mBikeInterface.queryBikeState(bikeNumber),
                new DefaultResponseDispatcher(dataListener));
    }
}
